package com.itcast.imageview;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
    private StringBuilder hobbys;
    private TextView hobby;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        hobbys = new StringBuilder();
    }
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        String motion = compoundButton.getText().toString();
        if (b) {
            if (!hobbys.toString().contains(motion)) {  // 检查是否已经存在该爱好
                if (hobbys.length() > 0) {
                    hobbys.append(", ");  // 如果已有内容，添加逗号分隔符
                }
                hobbys.append(motion);  // 添加新的爱好
            }
        } else {
            if (hobbys.toString().contains(motion)) {
                // 删除取消选择的爱好
                int start = hobbys.indexOf(motion);
                int end = start + motion.length();
                if (start > 0 && hobbys.charAt(start - 2) == ',') {
                    start -= 2;
                } else if (end < hobbys.length() && hobbys.charAt(end) == ',') {
                    end += 2;
                }
                hobbys.delete(start, end);
            }
        }
        hobby.setText(hobbys.toString());
    }
}
